﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;

namespace Shileme.Common.Helper
{
    /// <summary>
    /// 通用辅助方法类
    /// author      heyz
    /// </summary>
    public static class UtilHelper
    {

        /// <summary>
        /// 获取数据库主键
        /// authorr     heyz
        /// </summary>
        /// <returns></returns>
        public static  string GetGuid() {
            return Guid.NewGuid().ToString().Replace("-", ""); 
        }

        /// <summary>
        /// 获取SQL数据库最小时间
        /// author      heyz
        /// </summary>
        /// <returns></returns>
        public static DateTime GetSqlMinTime()
        {
            return (DateTime)System.Data.SqlTypes.SqlDateTime.MinValue;
        }



        /// <summary>
        /// 生成指定长度的随机字符串
        /// author      heyz
        /// createtime  2015-08-28
        /// </summary>
        /// <param name="intlen"></param>
        /// <returns></returns>
        public static string GetRoundStringByLen(int intlen = 16)
        {
            string strPwChar = "0123456789";
            string strRe = "";
            int iRandNum;
            Random rnd = new Random();
            for (int i = 0; i < intlen; i++)
            {
                iRandNum = rnd.Next(strPwChar.Length);
                strRe += strPwChar[iRandNum];
            }
            return strRe;
        }


        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="source">原内容</param>
        /// <returns>加密后内容</returns>
        public static string MD5Encrypt(string source)
        {
            // Create a new instance of the MD5CryptoServiceProvider object.
            System.Security.Cryptography.MD5 md5Hasher = System.Security.Cryptography.MD5.Create();

            // Convert the input string to a byte array and compute the hash.
            byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(source));

            // Create a new Stringbuilder to collect the bytes and create a string.
            StringBuilder sBuilder = new StringBuilder();

            // Loop through each byte of the hashed data and format each one as a hexadecimal string.
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("X2"));
            }

            // Return the hexadecimal string.
            return sBuilder.ToString();
        }
        
       
        public static WebResponse doPost(string url, string postData)
        {
            HttpWebRequest webRequest = null;
            try
            {
                //Thread.Sleep(this.defer);
                byte[] paramByte = Encoding.UTF8.GetBytes(postData); // 转化
                webRequest = (HttpWebRequest)WebRequest.Create(url);

                webRequest.Method = "POST";
                webRequest.ContentType = "application/x-www-form-urlencoded";
                webRequest.Referer = "http://bulo.hjenglish.com/app/app.aspx?aid=1040";
                webRequest.Accept = "application/x-shockwave-flash, image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-silverlight, */*";
                webRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; CIBA)";
                webRequest.ContentLength = paramByte.Length;

                Stream newStream = webRequest.GetRequestStream();
                newStream.Write(paramByte, 0, paramByte.Length);    //写入参数
                newStream.Close();
            }
            catch (Exception ce)
            {

            }

            return webRequest.GetResponse();
        }
        public static string ResponseToString(WebResponse response)
        {
            try
            {
                Encoding encoding = Encoding.Default;
                string ContentType = response.ContentType.Trim();
                if (ContentType.IndexOf("utf-8") != -1)
                    encoding = Encoding.UTF8;
                else if (ContentType.IndexOf("utf-7") != -1)
                    encoding = Encoding.UTF7;
                else if (ContentType.IndexOf("unicode") != -1)
                    encoding = Encoding.Unicode;

                StreamReader stream = new StreamReader(response.GetResponseStream(), encoding);
                string code = stream.ReadToEnd();
                stream.Close();
                response.Close();
                return code;
            }
            catch (Exception ce)
            {
                throw ce;
            }
        }
        /// <summary>
        /// 日期时间转换timestamp
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static long DateToTimeStamp(DateTime dt)
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            DateTime dtNow = dt;
            TimeSpan toNow = dtNow.Subtract(dtStart);
            string timeStamp = toNow.Ticks.ToString();
            timeStamp = timeStamp.Substring(0, timeStamp.Length - 7);
            return long.Parse(timeStamp);
        }

        /// <summary>
        /// MD5散列
        /// </summary>
        public static string MD5(string inputStr)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] hashByte = md5.ComputeHash(Encoding.UTF8.GetBytes(inputStr));
            StringBuilder sb = new StringBuilder();
            foreach (byte item in hashByte)
                sb.Append(item.ToString("x").PadLeft(2, '0'));
            return sb.ToString();
        }
        /// <summary>
        /// 获取随机数字验证码
        /// </summary>
        /// <param name="Length">验证码位数</param>
        /// <returns></returns>
        public static string getRadom(int Length)
        {
            var text2 = "";
            var random = new Random((int)DateTime.Now.Ticks);
            const string textArray = "0123456789";

            for (var i = 0; i < Length; i++)
            {
                text2 = text2 + textArray.Substring(random.Next() % textArray.Length, 1);
            }

            return text2;
        }
        /// <summary>
        /// 截取字符串 超过用...代替
        /// </summary>
        /// <param name="stringToSub"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public static string GetFirstString(string stringToSub, int length)
        {
            Regex regex = new Regex("[\u4e00-\u9fa5]+", RegexOptions.Compiled);
            char[] stringChar = stringToSub.ToCharArray();
            StringBuilder sb = new StringBuilder();
            int nLength = 0;
            bool isCut = false;
            for (int i = 0; i < stringChar.Length; i++)
            {
                if (regex.IsMatch((stringChar[i]).ToString()))
                {
                    sb.Append(stringChar[i]);
                    nLength += 2;
                }
                else
                {
                    sb.Append(stringChar[i]);
                    nLength = nLength + 1;
                }

                if (nLength > length)
                {
                    isCut = true;
                    break;
                }
            }
            if (isCut)
                return sb.ToString() + "..";
            else
                return sb.ToString();
        }
        /// <summary>
        /// 获取配置文件值
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string getConfig(string key)
        {
            return ConfigurationManager.AppSettings[key];
        }


        /// <summary>
        /// 返回当前时间时间戳
        /// author      heyz
        /// </summary>
        /// <returns></returns>
        public static string GetCurrentTimespan() {
            DateTime dt = DateTime.Now;
            TimeSpan ts = dt.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return dt.ToString("yyyyMMdd")+ Convert.ToInt64(ts.TotalSeconds).ToString();  
        }
        public static bool IsMobilePhone(string input)
        {
            string pattern = @"^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$";
              Regex regex = new Regex(pattern);
              return regex.IsMatch(input);
        }
        public static bool IsQQ(string input)
        {
            string pattern = @"^[0-9]{5,16}$";
            Regex regex = new Regex(pattern);
            return regex.IsMatch(input);
        }

        public static bool IsCode(string input)
        {
            string pattern = @"^[0-9]{6}$";
            Regex regex = new Regex(pattern);
            return regex.IsMatch(input);
        }
        /// <summary>
        /// 获得请求的ip
        /// </summary>
        /// <returns></returns>
        public static string GetIP()
        {
            string ip = string.Empty;
            if (HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
                ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
            else
                ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();

            if (string.IsNullOrEmpty(ip) || "::1".Equals(ip))
                ip = "127.0.0.1";
            return ip;
        }
        /// <summary>
        /// 发送手机短信
        /// </summary>
        /// <param name="phone"></param>
        /// <returns></returns>
        public static string SendMsg(string phone, string msg)
        {
            //POST
            StringBuilder sbTemp = new StringBuilder();

            sbTemp.AppendFormat("apikey=30780ab7ac406610aaf6c2a4fb989eba&username=dengfeng&password=xianghao1314&mobile={0}&content={1}", phone,msg);
            byte[] bTemp = System.Text.Encoding.GetEncoding("GBK").GetBytes(sbTemp.ToString());
            String result = PostRequest("http://m.5c.com.cn/api/send/?", bTemp);
            return result;
        }
        /// <summary>
        /// 发送手机验证码
        /// </summary>
        /// <param name="phone"></param>
        /// <returns></returns>
        public static string SendCode(string phone,string code)
        {
            //POST
            StringBuilder sbTemp = new StringBuilder();
         
            sbTemp.AppendFormat("apikey=30780ab7ac406610aaf6c2a4fb989eba&username=dengfeng&password=xianghao1314&mobile={0}&content={1}",phone,Shileme.Common.Helper.UtilHelper.getConfig("FindPassMessage").Replace("[Code]",code));
            byte[] bTemp = System.Text.Encoding.GetEncoding("GBK").GetBytes(sbTemp.ToString());
            String result = PostRequest("http://m.5c.com.cn/api/send/?", bTemp);
            return result;
        }
        //POST方式发送得结果
        private static String PostRequest(string url, byte[] bData)
        {
            System.Net.HttpWebRequest hwRequest;
            System.Net.HttpWebResponse hwResponse;

            string strResult = string.Empty;
            try
            {
                hwRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
                hwRequest.Timeout = 5000;
                hwRequest.Method = "POST";
                hwRequest.ContentType = "application/x-www-form-urlencoded";
                hwRequest.ContentLength = bData.Length;

                System.IO.Stream smWrite = hwRequest.GetRequestStream();
                smWrite.Write(bData, 0, bData.Length);
                smWrite.Close();
            }
            catch (System.Exception err)
            {
                //WriteErrLog(err.ToString());
                return strResult;
            }

            //get response
            try
            {
                hwResponse = (HttpWebResponse)hwRequest.GetResponse();
                StreamReader srReader = new StreamReader(hwResponse.GetResponseStream(), Encoding.ASCII);
                strResult = srReader.ReadToEnd();
                srReader.Close();
                hwResponse.Close();
            }
            catch (System.Exception err)
            {
                //WriteErrLog(err.ToString());
            }

            return strResult;
        }

        /// <summary>
        /// 返回插入交易日志sql
        /// </summary>
        /// <returns></returns>
        public static string GetTradeLogInsertSql() {
            return @" INSERT INTO dbo.DT_TradeLog
                    ( tid ,
                      tradeContent ,
                      memberid ,
                      TrialId ,
                      TrialNO ,
                      money ,
                      Point ,
                      createtime ,
                      tradetype ,
                      status ,
                      orderid
                    )
            VALUES  ( '{0}' , -- tid - char(32)
                      N'{1}' , -- tradeContent - nvarchar(150)
                      '{2}' , -- memberid - char(32)
                      '{3}' , -- TrialId - char(32)
                      '{4}' , -- TrialNO - char(32)
                      {5} , -- money - decimal
                      {6}, -- Point - int
                      '{7}' , -- createtime - datetime
                      {8} , -- tradetype - tinyint
                      {9}, -- status - tinyint
                      '{10}'  -- orderid - char(32)
                    )";
        }

        /// <summary>
        /// 返回插入订单日志sql
        /// </summary>
        /// <returns></returns>
        public static  string GetOrderLogInsertSql() {
            return @" INSERT INTO dbo.DT_OrderLog
                        ( LogId, LogContent, LogDate, OrderID )
                        VALUES  ( '{0}', -- LogId - char(32)
                                  '{1}', -- LogContent - varchar(200)
                                  '{2}', -- LogDate - datetime
                                  '{3}'  -- OrderID - char(32)
                                  ) ";
        }

        /// <summary>
        /// 返回插入申述sql
        /// </summary>
        /// <returns></returns>
        public static  string GetComplaintInsertSql(){
            return @" INSERT INTO dbo.BT_Complainid
                        ( complainid ,
                                  complainRemark ,
                                  orderid ,
                                  orderNo ,
                                  sell_id ,
                                  createtime ,
                                  picture,
                                compType
                                )
                        VALUES  ( '{0}' , -- complainid - char(32)
                                  '{1}' , -- complainRemark - varchar(500)
                                  '{2}' , -- orderid - char(32)
                                  '{3}' , -- orderNo - char(32)
                                  '{4}' , -- sell_id - char(32)
                                  '{5}' , -- createtime - datetime
                                  '{6}',  -- picture - varchar(50)
                                    {7}
                                )  ";
        }


        /// <summary>
        /// 返回插入站内私信sql
        /// </summary>
        /// <returns></returns>
        public static string GetMessageInsertSql() {
            return @" INSERT INTO dbo.DT_Message
                    ( MID ,
                      MContent ,
                      MType ,
                      MStatus ,
                      MemberID ,
                      CreateDate
                    )
            VALUES  ( '{0}' , -- MID - char(32)
                      '{1}' , -- MContent - text
                      {2}, -- MType - tinyint
                      {3}, -- MStatus - tinyint
                      '{4}' , -- MemberID - char(32)
                      '{5}'  -- CreateDate - datetime
                    ) ";
        }

        /// <summary>
        /// 返回插入财务日志sql
        /// </summary>
        /// <returns></returns>
        public static string GeFinanceLogInsertSql()
        {
            return @" INSERT INTO [shileme].[dbo].[DT_FinanceLog]([ID],[MemberID],[Amount],[FinanceType],[Status],[Remark],[UsedAmount],[CreateDate],[RechargeID],TradeNo)VALUES('{0}','{1}',{2},{3},{4},'{5}',{6},getdate(),'{7}','{8}')";
        }
    }
}
